package top.eggcode.security.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import top.eggcode.common.mvc.IpUtil;
import top.eggcode.spring.HttpServletUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * feign 请求拦截器
 *
 * @author ruoyi
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = HttpServletUtil.getRequest();
        Map<String, String> headers = HttpServletUtil.getHeaders(httpServletRequest);
        // 传递用户信息请求头，防止丢失
        String sessionId = headers.get("session-id");
        if (StringUtils.isNotEmpty(sessionId)) {
            requestTemplate.header("session-id", sessionId);
        }

        // 配置客户端IP
        requestTemplate.header("X-Forwarded-For", IpUtil.getAddress(HttpServletUtil.getRequest()));
    }
}